import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { HttpClient } from '@angular/common/http';

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Mp } from './mp';
import { MpTpl } from './mptpl';

@Injectable()
export class DataService {

  private headers = new Headers({'Content-Type': 'application/json'});
  private serverUrl = 'http://tssapi.yunkaodian.com/?service=';
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

  constructor(private http: Http, private httpc: HttpClient) { }

  /**
   * 平台列表
   * @returns {Promise<any>}
   */
  getMpList(): Promise<Mp[]> {
    const url = `${this.serverUrl}` + 'Tss.mpList';
    return this.http.get(url)
      .toPromise()
      .then(response => response.json().data as Mp[])
      .catch(this.handleError);
  }

  /**
   * 发送历史
   * @returns {Promise<any>}
   */
  getSendHistory(): Promise<any> {
    const url = `${this.serverUrl}` + 'Tss.sendHistory';
    return this.http.get(url)
      .toPromise()
      .then(response => response.json().data as any)
      .catch(this.handleError)
  }

  /**
   * 模板列表
   * @param mpid
   * @returns {Observable<R|T>}
   */
  getMpTpls(mpid: number): Observable<MpTpl[]> {
      const url = `${this.serverUrl}` + 'Tss.tplList' + `&mpId=${mpid}`;
      return this.http.get(url)
      .map(data => data.json().data as MpTpl[])
      .catch(this.handleError);
  }

  /**
   * 发送
   * @param mpid
   * @param tmpid
   * @returns {Observable<R|T>}
   */
  msgSend(mpid: number,tmpid: string): Observable<any> {
    const url = `${this.serverUrl}` + 'Tss.sendMsg' + `&mpId=${mpid}&tmpId=${tmpid}`;
    return this.http.get(url)
      .map(data => data.json().data as MpTpl[])
      .catch(this.handleError);
  }

  /**
   * 导入用户
   * @param mpid
   * @returns {Observable<R|T>}
   */
  inputUser(mpid: number): Observable<any> {
    const url = `${this.serverUrl}` + 'Tss.inputUser' + `&mpId=${mpid}`;
    return this.http.get(url)
      .map(data => data.json().data as any)
      .catch(this.handleError);

  }

}
